/*
 *所有关于formulasetting类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*formulasettingService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VolPro.Core.BaseProvider;
using VolPro.Core.Extensions.AutofacManager;
using VolPro.Entity.DomainModels;
using System.Linq;
using VolPro.Core.Utilities;
using System.Linq.Expressions;
using VolPro.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using SMes.DbMethod.IRepositories;
using VolPro.Core.ManageUser;
using Newtonsoft.Json;
using System.Net;
using System.Collections.Generic;

namespace SMes.DbMethod.Services
{
    public partial class formulasettingService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IformulasettingRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public formulasettingService(
            IformulasettingRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            WebResponseContent webResponse = new();
            AddOnExecute =(SaveModel saveModel) =>
            {
                saveModel.MainData.TryAdd("last_updated", DateTime.Now);
                saveModel.DetailData = [];
                string jsonStr = JsonConvert.SerializeObject(saveDataModel.Extra);
                var item = JsonConvert.DeserializeObject<List<process_baseparams>>(jsonStr);
                if (item == null || item.Count == 0)
                {
                    return webResponse.Error("配方相关参数不具备....请重新填写");
                }
                foreach (var i in item)
                {
                    var formuladetails = new formuladetails
                    {
                        FormulaName = i.Name,
                        GroupName = i.GroupName,
                        last_updated = DateTime.Now,
                        target_value = i.SetVal,
                        tolerance = i.Deviation,
                        IsManyFormula = false
                    };
                    Dictionary<string, object>? dicts = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(formuladetails));
                    if(dicts != null)
                    {
                        saveModel.DetailData.Add(dicts);
                    }
                }
                return webResponse.OK();
            };
            return base.Add(saveDataModel);
        }
        public override WebResponseContent Update(SaveModel saveDataModel)
        {
            //UserContext.Current.UserName
            WebResponseContent webResponse = new();
            UpdateOnExecute = (SaveModel saveModel) =>
            {
                saveModel.MainData.TryAdd("last_updated", DateTime.Now);
                saveModel.DetailData = [];
                string jsonStr = JsonConvert.SerializeObject(saveDataModel.Extra);
                var item = JsonConvert.DeserializeObject<List<process_baseparams>>(jsonStr);
                if (item == null || item.Count == 0)
                {
                    return webResponse.Error("配方相关参数不具备....请重新填写");
                }
                foreach (var i in item)
                {
                    var formuladetails = new formuladetails
                    {
                        Detail_Id = i.Id,
                        FormulaSetId = Convert.ToInt32(saveModel.MainData["FormulaSetId"]),
                        FormulaName = i.Name,
                        GroupName = i.GroupName,
                        last_updated = DateTime.Now,
                        target_value = i.SetVal,
                        tolerance = i.Deviation,
                        IsManyFormula = false
                    };
                    Dictionary<string, object>? dicts = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(formuladetails));
                    
                    if (dicts != null)
                    {
                        if (i.Id <1)
                        {
                            dicts.Remove("Detail_Id");
                        }
                        saveModel.DetailData.Add(dicts);
                    }
                }
                return webResponse.OK();
            };
            return base.Update(saveDataModel);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keys">删除的行的主键</param>
        /// <param name="delList">删除时是否将明细也删除</param>
        /// <returns></returns>
        public override WebResponseContent Del(object[] keys, bool delList = true)
        {
            WebResponseContent webResponse = new();
            //将keys转换为表的主键类型一致，用于下面的查询
            var ids = keys.Select(s => s.GetInt()).ToList();
            if(ids==null || ids.Count<1) return webResponse.Error("主键不符合规定....");
            var FormulaTags = _repository.FindAsIQueryable(x => ids.Contains(x.FormulaSetId)).Select(m => m.FormulaTag).ToList();
            if(FormulaTags==null || FormulaTags.Count<1) return webResponse.Error($"未找到主键相关的表数据{string.Join(" ", ids)}....");
            //删除后处理
            //删除的行的主键
            DelOnExecuted = (object[] _keys) =>
            {
                try
                {
                    var processformulamains = _repository.DbContext.Set<processformulamain>().Where(m => FormulaTags.Contains(m.FormulaTag));
                    _repository.DbContext.Set<processformulamain>().RemoveRange(processformulamains);
                    _repository.DbContext.SaveChanges();
                    return webResponse.OK();
                }catch(Exception ex)
                {
                    return webResponse.Error("删除配方关联主表ex:"+ex.Message);
                }
               
            };
            return base.Del(keys, delList);
        }
    }
}
